/**
 * Created by moko1988 on 15/12/1.
 */
define([
    'backbone',
    'models/numberPrice/list',
    'text!templets/numberPrice/list.html',
    'text!templets/numberPrice/list-modal-add.html',
    'text!templets/numberPrice/list-modal-add-insert.html',
    'utils/dataTableUtil',
    'utils/urlUtil',
    'jquerypage',
    'select2',
    'moment'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    ModalAddIn,
    DataTable,
    UrlUtil
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun', //添加资源
            'click [role=edit]': 'editFun', //修改资源
            'click [role=del]': 'delFun', //删除资源
            'click [role=close]': 'closeFun', //关闭
            'click [role=saveAdd]': 'saveAdd',    //保存添加
            'change #pageSize': 'changePageSize', //选择分页宽度
            'click [role=rank]': 'rank', //排序
            'click [role=review]': 'review', //审核
             'click [role=saveChange]': 'saveChange',//保存修改 
            'click [role=recommend]': 'recommend', //推荐
            'click #checkAll': 'checkAll', //全选、取消
            'click input[name=idarr]': 'checkItem' //选择、取消单条记录
       
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.idArr = [];
            this.categoryid = '';
            $('#pageSize').select2();
            this.render();
        } ,
       
        /*排序*/
        rank: function(e) {
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },
        /*选择分页宽度*/
        changePageSize: function(e) {
            var $target = $(e.currentTarget),
                val = $target.val();
            this.listRows = val;
            this.render();
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                data: {
                    page: this.page,
                    page_size: this.listRows,
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                         o.checkbox = '<input type="checkbox" value="'+ o.price_id +'" name="idarr">';

                    })
                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '所属渠道', '所属公众号', '单图文',  '多图文第一条' , '多图文第二条', '多图文第三条'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'price_id'),
                            _.pluck(data,'corporate_name'),
                            _.pluck(data,'name'),
                            _.pluck(data,'single_price'),
                            _.pluck(data,'one_price'),
                            _.pluck(data,'two_price'),
                            _.pluck(data,'three_price')
                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });
                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
        /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.searchCharge();
        },
       //添加
        addFun: function() {
            $(this.el).append(ModalAddIn);
            var $myModal = $('#myModal');
            $myModal.find('h4').html('添加公众号报价');
            $myModal.off();
            $myModal.modal();
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });

                _this = this; 

            Model.fetchCategory_number({
                    type: 'get',
                    success: function(map) {
                        var opts = '<option value="">选择公众号</option>',
                            category = {};
                        _.each(map, function(o){
                            category[o.public_id] = o;

                            opts += '<option value="'+o.public_id+'">'+ o.name+'</option>';
                        });
                        _this.categoryOpts = opts;
                        _this.categoryObj = category;
                        $('#Allnumbers').html(opts).prop('disabled',false).select2();
                        $('[role=add]').prop('disabled',false);
                    }
                })


        },
        //添加提交
         saveAdd: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveAdd]'),

                isOk,
                single,
                first,
                second,
                third;

                //获取游戏名称的值
                single = $('#single').val();
                //获取分层比例的值
                first = $('#first').val();
                //获取游戏链接的值
                second = $('#second').val();
                //获取备注的值
                third = $('#third').val();

                 //获取下拉框的值      
                selOpt = $('#Allnumbers option:selected').val();

                isOK = this.checkForm();
               
                if(isOK){
                    Model.insert({
                     type: 'post',
                      data: {
                       single:single,
                       first: first,
                       second:second,
                       third: third,
                       selOpt:selOpt
                    },  
                     success: function() {
                         subBtn.html('提 交').prop('disabled', false);
                            jAlert('提交成功', function() {
                                 $myModal.modal('hide');
                                _this.render();
                             })
                        }                
                  })
                }
        },

        /*修改*/
        editFun: function(e){
             $(this.el).append(ModalAdd);
            var $target = $(e.currentTarget),
                $myModal = $('#myModal'),
                id = this.idArr[0],
                _this = this;           
             if (this.idArr.length) {   
                $myModal.off();
                $myModal.modal();
                $myModal.find('h4').html('修改公众号报价');
                $myModal.find('[role=save]').prop('disabled', true);
                $('#add-category').prop('disabled',false).html(this.categoryOpts);
                /*弹窗关闭*/
                $myModal.on('hidden.bs.modal', function(e) {
                    $myModal.remove();
                });
                $('#loading').html(loading);
                $('#data-form').hide();

                Model.fetchInfo({
                    data: {
                        id: id
                    },
                    success: function(map) {
                        $myModal.find('input[name=id]').val(id);
                        $myModal.find('input[name=single]').val(map.single_price);
                        $myModal.find('input[name=first]').val(map.one_price);
                        $myModal.find('input[name=second]').val(map.two_price);
                        $myModal.find('input[name=third]').val(map.three_price);

                        $('#loading').html('');
                        $('#data-form').show();
                        $myModal.find('[role=save]').prop('disabled', false);
                    }
                 });
            } else {
                jAlert('请选择要操作的数据');
            }
        },
        //提交修改
         saveChange : function() {
            var _this = this,
                id = this.idArr[0],
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveChange]'),
              
                single,
                first,
                second,
                third;

                //获取游戏名称的值
                single = $('#single').val();
                //获取分层比例的值
                first = $('#first').val();
                //获取游戏链接的值
                second = $('#second').val();
                //获取备注的值
                third = $('#third').val();

                subBtn.html('正在提交..').prop('disabled', true);
                 $myModal.remove();
                Model.update({
                    type: 'post',
                    data: {
                        id: id,
                       single:single,
                       first: first,
                       second:second,
                       third: third
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            _this.render();
                        });
                    }
                })

        
        },

        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.parents('tr').attr('data-id'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                jConfirm('确定要删除？', function(s) {
                    if (s) {
                        Model.delete({
                            data: {
                                id: id
                            },
                            success: function(map) {
                                jAlert('删除成功', function() {
                                    _this.idArr = [];
                                    _this.render();
                                })
                            }
                        })
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }

        },



        checkForm: function() {
            var $form = $('[role=form]'),
               
                //下拉框
                $select = $('#Allnumbers');
                $selOpt = $('#Allnumbers option:selected');

                getTip = function(e) {
                    var text = e.siblings('label.control-label').html();
                    // text = text.substr(0, text.length - 1);
                    return text;
                },
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
                
               
                //下拉框
                if ($.trim($selOpt.val()) == '') {
                     errShow($select, '请选择公众号');
                } 

            return rest;
        },


    })
    return view;
})

